import { getInfo } from "@/api/login";
import { getShopInfo  } from '@/api/shop/shopInfo'
const state = {
  userId: null,
  username: null,
  avatar: null,
  shopId: null,
  shopName: null,
  shopInfo: null
};

const mutations = {
  SET_USER_ID(state, value) {
    state.userId = value;
  },

  SET_USER_NAME(state, value) {
    state.username = value;
  },
  SET_AVATAR(state, value) {
    state.avatar = value;
  },
  SET_SHOP_ID: (state, value) => {
    state.shopId = value
  },
  SET_SHOP_NAME(state, value) {
    state.shopName = value;
  },
  SET_SHOP_INFO: (state, value) => {
    state.shopInfo = value
  }
  
};

/**获取用户信息 */
const actions = {
  async getUserInfo(context) {
    const res = await getInfo();
    if (res.code == 200) {
      console.log("用户Id", res.data.userID);
      context.commit("SET_USER_ID", res.data.userID);
      context.commit("SET_USER_NAME", res.data.username);
      context.commit("SET_AVATAR", res.data.avatar);

      const response = await getShopInfo(res.data.userID);
      if (response.code === 200) {
        context.commit("SET_SHOP_ID", response.data.id);
        context.commit("SET_SHOP_NAME", response.data.shopName);
      }
    }
  },
 // 新增：获取并存储店铺信息
  async getAndStoreShopInfo(context) {
    try {
      // 使用用户ID作为商家ID来获取店铺信息
      const response = await getShopInfo(context.state.userId);
      if (response.code === 200 && response.data) {
        const shopInfo = response.data;
        context.commit("SET_SHOP_ID", shopInfo.id); // 存储店铺ID
        context.commit("SET_SHOP_INFO", shopInfo); // 存储完整的店铺信息
        return true;
      } else {
        console.error('获取店铺信息失败:', response.msg);
        return false;
      }
    } catch (error) {
      console.error('获取店铺信息异常:', error);
      return false;
    }
  },

  /**退出登录 */
  logOut(context) {
    context.commit("SET_USER_ID", null);
    context.commit("SET_USER_NAME", null);
    context.commit("SET_AVATAR", null);
    context.commit("SET_SHOP_ID", null);
    context.commit("SET_SHOP_NAME", null);
  },
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
